//
//  CardListViewController.m
//  RONGAO
//
//  Created by Kendama on 2018/2/26.
//  Copyright © 2018年 wei wang. All rights reserved.
//

#import "CardListViewController.h"
#import "JXButton.h"
#import "AddFingerprintViewController.h"
#import "GetPwdListApi.h"
#import "MemberPwdModel.h"
#import "WiFiSendDataManager.h"
#import "AddSuccessViewController.h"

@interface CardListViewController ()<UITableViewDelegate,UITableViewDataSource>

/** UItableView **/
@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *dataSoure;
@property(nonatomic,strong) JXButton *addButton;
@property (nonatomic ,strong)NSIndexPath *deleteIndexPath;

@end

@implementation CardListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteCallBack:) name:DeleteFingerprintOrCardOrPasswordNotification object:nil];

}

- (void)deleteCallBack:(NSNotification *)notice {
    NSString *str = notice.object;
    NSString *subStr = [str substringFromIndex:6];
    
    if ([subStr intValue] == 1) {
        if (self.deleteIndexPath) {
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [self.dataSoure removeObjectAtIndex:self.deleteIndexPath.row];
            [self.tableView deleteRowsAtIndexPaths:@[self.deleteIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
            self.deleteIndexPath = nil;
        }
        
    } else if ([subStr intValue] == 2) {
        [SVProgressHUD showErrorWithStatus:@"删除失败,管理员指纹不能删除"];
    } else {
        [SVProgressHUD showErrorWithStatus:@"删除失败"];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateDataSource];
}

#pragma mark - --------------------------点击事件--------------------------
- (void)didClickAddButton
{
    [[AlertViewManager shareManager] initWithMessage:@"请将门锁唤醒，点击门锁上面的按钮8+按钮#进入设置模式，完成此操作后点击App上的确定按钮" cancleButtonTitle:@"确定" clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
        if (buttonIndex == 0)
        {
            [[WiFiSendDataManager defaultService] addCard:_deviceMac];
            AddFingerprintViewController *vc = [AddFingerprintViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}

#pragma mark - --------------------------事件处理--------------------------
- (void)updateDataSource
{
    [GetPwdListApi getMemberPwdListDeviceMac:_deviceMac type:2 success:^(NSArray<MemberPwdModel *> *list) {
        [self.dataSoure removeAllObjects];
        [self.dataSoure addObjectsFromArray:list];
        [self.tableView reloadData];
    } fail:^(NSDictionary *dic) {
        
    }];
}


#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSoure.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 56;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}

#pragma mark - --------------------------UITableView delegate--------------------------

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    MemberPwdModel *model = self.dataSoure[indexPath.row];
    cell.textLabel.text = model.name;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    __weak typeof(self) weak = self;
    MemberPwdModel *model = self.dataSoure[indexPath.row];
    AddSuccessViewController *vc = [AddSuccessViewController new];
    vc.memberModel = model;
    vc.callBack = ^{
        [weak updateDataSource];
    };
    vc.type = 3;
    [self.navigationController pushViewController:vc animated:YES];
}




- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}


#pragma mark 在滑动手势删除某一行的时候，显示出更多的按钮
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 添加一个删除按钮
    
    __weak typeof(self) weakself = self;
    //    DTDevice *info = self.dataSoure[indexPath.row];
    
    UITableViewRowAction *deletRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        MemberPwdModel *model = self.dataSoure[indexPath.row];
        self.deleteIndexPath = indexPath;
        [[WiFiSendDataManager defaultService] deletePassword:self.deviceMac value:model.id];
        [tableView reloadData];
        [SVProgressHUD showWithStatus:nil];
        [SVProgressHUD dismissWithDelay:5];
        
        //        [[DTCloudManager defaultJNI_iOS_SDK] unBindDeviceByUUID:info.deviceUUID successCallback:^(NSDictionary *dic) {
        //
        //            [weakself.dataSoure removeObject:info];
        //            [weakself.tableView reloadData];
        //
        //        } errorCallback:^(NSDictionary *dic) {
        //
        //            [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
        //        }];
        
    }];
    
    deletRowAction.backgroundColor = [UIColor colorWithHexString:@"f8533d"];
    
    return @[deletRowAction];
}


#pragma mark - --------------------------懒加载--------------------------
- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (NSMutableArray *)dataSoure
{
    
    if (!_dataSoure)
    {
        _dataSoure = [NSMutableArray arrayWithArray:@[]];
    }
    return _dataSoure;
}

- (JXButton *)addButton
{
    if(!_addButton)
    {
        UIView *superView = self.view;
        _addButton = [[JXButton alloc]init];
        //[superView addSubview:_addButton];
        [_addButton setImage:[UIImage imageNamed:@"bnt_add_nor"] forState:UIControlStateNormal];
        [_addButton setTitle:@"添加卡片" forState:UIControlStateNormal];
        [_addButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [_addButton addTarget:self action:@selector(didClickAddButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addButton;
}


#pragma mark - --------------------------约束--------------------------
- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(superView);
    }];
    
//    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(superView.mas_centerX);
//        make.bottom.mas_equalTo(superView.mas_bottom).with.offset(pxScaleHeight(-100));
//        make.height.mas_equalTo(40);
//    }];
    
}

#pragma mark - --------------------------导航栏--------------------------
- (void)setNavigationStyle
{
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"卡片列表" titleColor:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
